<?php
/**
 * $Id: javascript.php 701 2010-09-03 09:09:48Z shrey $
 * 
 * Extended Javascript helper
 * 
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * @version 			$Rev: 701 $
 * @lastModifiedBy		$LastChangedBy: shrey $
 * @lastChanged			$Date: 2010-09-03 14:39:48 +0530 (Fri, 03 Sep 2010) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */
	App::import('Helper','BaseJavascript');
	class JavascriptHelper extends BaseJavascriptHelper
	{
		protected $compressedFileStore;
		var $inLayout = false;
		
		function beforeLayout()
		{
			$this->inLayout = true;
			parent::beforeLayout();
		}
		function afterLayout()
		{
			$this->inLayout = false;
		}
		private function compress($path)
		{
			if(!is_object($this->compressedFileStore))
			{
				App::import('Vendor','Cms.compression/CompressionFileStore');
				$this->compressedFileStore = new CompressionFileStore(CompressionFileStore::TYPE_JS,$this->webroot);
			}
			$fn = 'addPreFile';
			if($this->inLayout == true)
			{
				$fn = 'addPostFile';
			}
			$this->compressedFileStore->$fn($path);
		}
		
		function getCompressedJs($name = 'combined')
		{
			if(cr('App.cssCompression') == true && is_object($this->compressedFileStore))
			{
				
				$url = $this->compressedFileStore->getCompressedFileUrl($name);
				return parent::link($url);
			}
		}
		
		function link($url,$inline = true)
		{
			$assetCompression = cr('App.cssCompression');
			$actualInline = $inline;
			//need to add to compression even when it is inline false;
			if($assetCompression)
			{
				$inline = true;
			}
			$out = parent::link($url,$inline);
			if($assetCompression && preg_match('/<script.+><\/script>/',$out))
			{
				$src = null;
				$matches = array();
				preg_match_all('/src="(.+)"/',$out,$matches);
				if(isset($matches[1][0]))
				{
					$src = $matches[1][0];
				}
				if($src)
				{
					$this->compress($src);
				}
				$out = null;
			}
			return $out;
		}
	} 
?>